// 加载运行时配置获取服务器基础路径
const blacklist = ['/shopcart/list']

export type CommonResult<T> = {
    result: number;
    message: string;
    data: T,
    token: string | null;
    verifyResult: string | null;
}

let PROXY_PREFIX: string| null = null;

//@ts-ignore
export const fetchData = <T>(url: string, configs = {}) : Promise<CommonResult<T>> => {
    const config = useRuntimeConfig();
    const nuxtApp = useNuxtApp();
    // 根据环境判断代理前缀
    // if(PROXY_PREFIX === null){
    //     PROXY_PREFIX = process.env.NODE_ENV === 'development' ? config?.public?.DEV_PREFIX as string ?? "/dev": "https://localhost:3000"
    // }
    return new Promise((resolve, reject) => {
        useFetch(config.public.VITE_BASE_URL + url, {
            // 请求拦截器
            onRequest({ options }) {
                // 黑名单判断(需要token认证)
                if (blacklist.find(item => url.endsWith(item))) {
                    let accessToken = useUserStore().getToken();
                    if(accessToken){
                        options.headers = options.headers || {};
                        options.headers = {
                            //@ts-ignore
                            'KYLINTOKEN': accessToken,
                            "Cookie": `token=${accessToken}`,
                            ...options.headers,
                        }
                    }else {
                        nuxtApp.runWithContext(() => {
                            navigateTo({
                                path: '/login',
                                query:{
                                    result: 401,
                                    message: '登录信息失效, 请重新登录'
                                }
                            })
                        })
                    }
                }
            },
            // 响应拦截器
            onResponse({ response }) {
               if(response.status >= 200 && response.status < 300){
                let { result, data, message, token } = response._data
                if(result === 0){ // 正常情况（处理token续期的问题）
                    if(import.meta.client && token && token.length > 0){
                        console.log('token续期', data)
                        localStorage.setItem('access_token', token)
                    }
                }else{ // 异常情况
                    if(import.meta.client){ // 客户端处理
                        ElMessage.error(message)
                        if(result === -4000 || result === -4001 || result === -4003){
                            // 需要清空系统资源
                            nuxtApp.runWithContext(() => {
                                navigateTo({ path: '/login' })
                            })
                        }
                    }else{ // 服务端处理
                        nuxtApp.runWithContext(() => {
                            navigateTo({
                                path: '/requestError',
                                query:{
                                    result: response?._data?.result,
                                    message: response?._data?.message
                                }
                            })
                        })
                    }
                }
               }
            },
            onResponseError({ response }) {
                if(import.meta.client){
                    ElMessage.error(response?._data?.message)
                }else{
                    nuxtApp.runWithContext(() => {
                        navigateTo({
                            path: '/requestError',
                            query:{
                                result: response?._data?.result,
                                message: response?._data?.message
                            }
                        })
                    })
                }
            },
            ...configs
        }).then(res => {
            resolve(res.data.value as CommonResult<T>)
        }).catch(err => {
            reject(err)
        })
    })
}

export const fetchGet = <T>(url: string, params = {} , configs = {}) : Promise<CommonResult<T>> => {
    return fetchData<T>(url, {
        method: "get",
        query : params,
        ...configs
    })
}

export const fetchPost = <T>(url: string, params: Object| FormData = {}, configs = {}) : Promise<CommonResult<T>> => {
    return fetchData<T>(url, {
        method: "post",
        body: params,
        ...configs
    })
}